package com.yager.service.impl;


import com.yager.mapper.CollectionMapper;
import com.yager.mapper.HouseMapper;
import com.yager.mapper.OrderMapper;
import com.yager.mapper.UserMapper;
import com.yager.model.House;
import com.yager.model.User;
import com.yager.service.UserService;
import com.yager.util.EncryptUtil;
import com.yager.util.NameUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HouseMapper houseMapper;

    @Override
    public int registerNewUser(MultipartFile file, String name, String mobile, String email, String pwd) {
        String max=userMapper.findMaxId();
        max=max.substring(1);

        Integer i=Integer.parseInt(max);
        i++;
        String id="U";

        if(i<10) id=id+"00"+i.toString();
        else if(i<100) id=id+"0"+i.toString();
        else id=id+i.toString();

        EncryptUtil eu=new EncryptUtil();
        String truePwd=eu.EncriptByMD5(pwd);

        User user=new User(id,name,mobile,email,truePwd);
        user.setUserstatus(true);
        user.setUsergrade(60);

        //在数据库中检查是否有号码或者用户名重复的用户
        //检查手机号重复
        if(userMapper.getSameMobileCount(mobile)>0) return 0;

        //检查用户名重复
        if(userMapper.getSameNameCount(name)>0) return -1;

        if(file.isEmpty()){
            user.setUserimage("default.jpg");
        }
        else {
            /*生成图片新的随机名字*/
            String oldImgName = file.getOriginalFilename();
            String imgSuffix = oldImgName.substring(oldImgName.lastIndexOf("."));
            NameUtil nu = new NameUtil();
            String imgName = nu.GeneratorUserImgName()+imgSuffix;
            /*生成图片的存放目录*/
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = simpleDateFormat.format(new Date());

            user.setUserimage(datePath + "/" + imgName);
            System.out.println(user.getUserimage());

            File targetFile = new File("D://img/user/"+datePath);
            if (!targetFile.exists()) targetFile.mkdirs();
            /*指定图片名称*/
            File trueTargetFile = new File(targetFile,imgName);
            try {
                file.transferTo(trueTargetFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String datetime=sdf.format(new Date());
        Date date= null;
        try {
            date = sdf.parse(datetime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        user.setUserdate(date);



        userMapper.insert(user);
        return 1;
    }

    @Override
    public User getUserById(String id) {
        User user=userMapper.selectByPrimaryKey(id);
        System.out.println(user);
        return user;
    }

    @Override
    public void updateUserInfo(User user,MultipartFile file) {

        if(file.isEmpty()){
            user.setUserimage(null);
        }
        else {
            /*生成图片新的随机名字*/
            String oldImgName = file.getOriginalFilename();
            String imgSuffix = oldImgName.substring(oldImgName.lastIndexOf("."));
            NameUtil nu = new NameUtil();
            String imgName = nu.GeneratorUserImgName()+imgSuffix;
            /*生成图片的存放目录*/
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String datePath = simpleDateFormat.format(new Date());

            user.setUserimage(datePath + "/" + imgName);
            System.out.println(user.getUserimage());

            File targetFile = new File("D://img/user/"+datePath);
            if (!targetFile.exists()) targetFile.mkdirs();
            /*指定图片名称*/
            File trueTargetFile = new File(targetFile,imgName);
            try {
                file.transferTo(trueTargetFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        userMapper.updateByPrimaryKeySelective(user);
        System.out.println("update user");
    }

    @Override
    public List<User> getAllUsers() {
        List<User> list=new ArrayList<>();
        list=userMapper.getAllUsers();
        return list;
    }

    @Override
    public boolean login(String mobile, String pwd) {
        User target=null;
        target=userMapper.selectByMobileOrNameOrEmail(mobile);

        String truePwd=null;
        EncryptUtil eu=new EncryptUtil();

        if (target==null){
            System.out.println("用户不存在");
            return false;
        }
        if(!target.getUserstatus()){
            System.out.println("用户已注销");
            return false;
        }
        truePwd=eu.EncriptByMD5(pwd);
        System.out.println("输入密码："+pwd+"    加密密码："+truePwd+"    数据库密码："+target.getUserpwd());
        if(truePwd.equals(target.getUserpwd())){
            System.out.println("其实已经成功了");
            return true;
        }
        return false;
    }

    @Override
    public void deleteUserById(String id) {
        userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void changeUserStatusById(String id) {
        User user=userMapper.selectByPrimaryKey(id);
        if(user.getUserstatus()){
            user.setUserstatus(false);
        }
        else{
            user.setUserstatus(true);
        }
        userMapper.updateByPrimaryKey(user);
    }

    @Override
    public User getUserByMobile(String mobile) {
        User user=userMapper.selectByMobile(mobile);
        return user;
    }

    @Override
    public void changeUserPwd(String userid,String newpwd) {
        EncryptUtil eu=new EncryptUtil();
        String realnewpwd=eu.EncriptByMD5(newpwd);

        User user=new User();
        user.setUserid(userid);
        user.setUserpwd(realnewpwd);
        userMapper.updateByPrimaryKeySelective(user);
        System.out.println("已经修改id为："+userid+"的用户的新密码为："+newpwd+" 并加密为："+realnewpwd);
    }

    @Override
    public User getUserByMobileOrNameOrEmail(String str) {
        return userMapper.selectByMobileOrNameOrEmail(str);
    }

    @Override
    public void killUser(String userid) {
        List<House> list=houseMapper.selectHouseByUserId(userid);
        for(House h:list){
            houseMapper.removeOrderByHouseId(h.getHouseid());
            houseMapper.removeCollectionByHouseId(h.getHouseid());
        }
        userMapper.deleteUserHouses(userid);
        userMapper.deleteUserOrders(userid);
        userMapper.deleteUserCollections(userid);
    }
}


